package com.softWang.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.softWang.common.exception.LogicException;
import com.softWang.common.utils.SecurityUtils;
import com.softWang.system.constants.SystemParamterContants;
import com.softWang.system.mapper.SystemParameterMapper;
import com.softWang.system.mapper.SystemUsersMapper;
import com.softWang.system.po.SystemParameter;
import com.softWang.system.po.SystemUsers;
import com.softWang.system.controller.vo.systemUserProfile.ChangePasswordParam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class SystemUserProfileService  {
    @Resource
    private SystemUsersMapper systemUsersMapper;
    @Resource
    private SystemParameterMapper systemParameterMapper;

    public void changePassword(ChangePasswordParam param) throws Exception {
        Long userId = SecurityUtils.getUserId();
        SystemUsers user = systemUsersMapper.selectById(userId);
        String password = user.getPassword();
        String verifyPassword = param.getOldPassword().toUpperCase();
        if (!password.equals(verifyPassword)) {
            throw new LogicException("旧密码错误");
        }
        String newPassword = param.getPassword().toUpperCase();
        user.setPassword(newPassword);

        // 更新密码有效期
        SystemParameter passwordValidDaysP = systemParameterMapper.selectOne(new LambdaQueryWrapper<SystemParameter>().eq(SystemParameter::getPkey, SystemParamterContants.USER_PASS_VALID_DAYS));
        if(passwordValidDaysP==null){
            throw new LogicException("无法获得参数:"+ SystemParamterContants.USER_PASS_VALID_DAYS);
        }
        String days = passwordValidDaysP.getPvalue();
        Integer validDays = Integer.parseInt(days);
        LocalDateTime validDate = LocalDateTime.now().plusDays(validDays);
        user.setPassValidDate(validDate);
        systemUsersMapper.updateById(user);
    }
}
